<template>
  <div :class="{'mobile-create': showMobilePage}" class="sign-detail-container">
    <div class="sign-detail-content">
      <el-form ref="formInfo" :model="formInfo" :rules="rules" :label-position="formAlign" label-width="100px">
        <Title title="询价内容" style="font-size:16px; margin:10px 0 16px; padding-left: 24px"/>
        <el-row type="flex" class="flex-wrap">
          <el-col :span="12">
            <el-form-item label="创建人:" class="no-required creator">
              <ToolTip :content="formInfo.creator" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="所属部门"
              prop="departmentId">
              <el-cascader
                v-model="formInfo.departmentId"
                :show-all-levels="false"
                :options="deptTreeList"
                :props="{
                  emitPath:false,
                  value: 'id',
                  label: 'name',
                  checkStrictly: true,
                  multiple: false,
                }"
                popper-class="tag-overflow"
                placeholder="请选择所属部门"
                size="small"
                class="width240"
                collapse-tags
                filterable
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="询价标题" prop="title">
              <el-input v-model="formInfo.title" size="small" class="width240" maxlength="50" placeholder="请输入"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="价格有效期" prop="priceTime">
              <el-date-picker
                v-model="formInfo.priceTime"
                :editable="false"
                :picker-options="pickerOptions"
                type="daterange"
                class="width240"
                size="small"
                format="yyyy/MM/dd"
                value-format="timestamp"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="询价说明" prop="description" class="no-required textarea-class">
              <el-input v-model="formInfo.description" type="textarea" name="description" maxlength="200" placeholder="请输入询价说明" resize="none"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :style="`${showMobilePage?'margin-bottom: 16px':''}`" label="服务号通知" prop="enableNotification" class="no-required">
              <el-radio-group v-model="formInfo.enableNotification">
                <el-radio :label="1"><span style="font-size: 14px">开启</span></el-radio>
                <el-radio :label="0"><span style="font-size: 14px">关闭</span></el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <fixed-pagination>
        <div v-if="!showMobilePage" class="center">
          <el-button type="info" size="small" class="back-btn empty-btn-style" style="padding: 0 12px" @click="previewFields()">查看询价字段</el-button>
          <el-button v-if="canSaveDraft" :loading="draftLoading" type="info" size="small" class="back-btn empty-btn-style" @click="saveDraft()">保存草稿</el-button>
          <el-button :loading="addLoading" type="primary" size="small" class="submit-btn" @click="handleCreate()">发起询价</el-button>
          <el-button class="back-btn cancel-btn-style" size="small" @click="toBack()">取消</el-button>
        </div>
        <div v-else class="center">
          <MoreOperateBtn>
            <el-dropdown-item v-if="canSaveDraft" :disabled="addLoading" style="width:80px;text-align: center" @click.native="previewFields()">
              <div>查看询价字段</div>
            </el-dropdown-item>
            <el-dropdown-item v-if="canSaveDraft" :disabled="addLoading" style="width:80px;text-align: center" @click.native="saveDraft()">
              <div>保存草稿</div>
            </el-dropdown-item>
            <el-dropdown-item style="width:80px;text-align: center" @click.native="toBack()">
              <div>取消</div>
            </el-dropdown-item>
          </MoreOperateBtn>
          <el-button :loading="addLoading" type="primary" size="small" class="submit-btn" style="flex:1" @click="handleCreate()">发起询价</el-button>
        </div>
      </fixed-pagination>
    </div>
    <previewFields ref="previewFields"/>
    <FlyLinkedAccount ref="flyLinkedAccountRef" dialog-title="选择要询价的账号" show-price-status show-notice-status section-title="询价账号" />
  </div>
</template>
<script>
// 组件
import Title from '@/components/Title';
import FlyLinkedAccount from '@/components/FlyLinkedAccount';
import previewFields from '../components/previewFields';
// api methods
import { getDepartmentAll } from '@/api/config';
import { queryPriceCreate, queryPriceInfo } from '@/api/flyPrice';
import { showModal } from '@/utils/message';
import { mapState } from 'vuex';
import mobileCreate from '@/mixins/mobileCreate';
export default {
  components: {
    Title,
    FlyLinkedAccount,
    previewFields
  },
  mixins: [mobileCreate],
  data() {
    return {
      id: '',
      formInfo: {
        creator: '',
        departmentId: '',
        title: '',
        description: '',
        priceTime: [],
        queryPriceAdvises: [], // 询价通知表
        enableNotification: 1
      },
      isCreateNew: false,
      deptTreeList: [],
      rules: {
        departmentId: [{ required: true, trigger: 'change', message: '请选择所属部门' }],
        title: [{ required: true, trigger: 'blur', message: '请输入询价标题' }],
        priceTime: [{ required: true, trigger: 'change', message: '请选择价格有效期' }],
        enableNotification: [{ required: true, trigger: 'change', message: '请选择服务号通知' }]
      },
      isDraft: false,
      addLoading: false,
      draftLoading: false
    };
  },
  computed: {
    ...mapState({
      'userInfo': state => state.user.userInfo
    }),
    canSaveDraft() {
      return !this.id || this.isDraft || this.isCreateNew;
    },
    pickerOptions() {
      return {
        shortcuts: [{
          text: '上月',
          onClick(picker) {
            const now = new Date();
            const year = now.getFullYear();
            const month = now.getMonth();
            const start = new Date(year, month - 1, 1, 0, 0, 0);
            const end = new Date(new Date(year, month, 1).setHours(0, 0, 0, 0) - 1);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '本月',
          onClick(picker) {
            const now = new Date();
            const year = now.getFullYear();
            const month = now.getMonth();
            const start = new Date(year, month, 1, 0, 0, 0);
            const end = new Date(new Date(year, month + 1, 1).setHours(0, 0, 0, 0) - 1);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '下月',
          onClick(picker) {
            const now = new Date();
            const year = now.getFullYear();
            const month = now.getMonth();
            const start = new Date(year, month + 1, 1, 0, 0, 0);
            const end = new Date(new Date(year, month + 2, 1).setHours(0, 0, 0, 0) - 1);
            picker.$emit('pick', [start, end]);
          }
        }]
      };
    }
  },
  created() {
    // 账号资源页面快速发起时需要选中账号
    if (this.$route.query.fromResource) {
      this.$refs['flyLinkedAccountRef'].setBoundAccountData();
    }
    this.id = Number(this.$route.query.id);
    this.isDraft = Boolean(this.$route.query.isDraft);
    this.isCreateNew = Boolean(this.$route.query.createNew);
    this.load();
    if (this.id) { // 编辑或者再次发起（复制）
      this.getInfo();
    } else { // 新建
      this.initData();
      this.initTitle();
    }
  },
  beforeRouteEnter(to, from, next) {
    if (from.name === 'flyPriceDetail') {
      to.meta.isDetail = true;
    } else {
      to.meta.isDetail = false;
    }
    next();
  },
  beforeRouteLeave(to, from, next) {
    if (this.$route.query.fromResource) {
      sessionStorage.removeItem('inBoundAccountData');
    }
    next();
  },
  methods: {
    load() {
      this.queryDeptTreeList();
    },
    initData() {
      this.formInfo.creator = this.userInfo.userName;
      this.formInfo.departmentId = this.userInfo.currentDeptIds[0];
    },
    initTitle() {
      const month = ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'];
      this.formInfo.title = `${month[new Date().getMonth()]}询价来啦~`;
    },
    // 获取详情
    getInfo() {
      queryPriceInfo(this.id).then(res => {
        if (res.code !== 200) {
          this.$message.error(res.message);
          return;
        }
        if (res.data.priceStartTime && res.data.priceEndTime) { res.data.priceTime = [res.data.priceStartTime * 1000, res.data.priceEndTime * 1000]; } else (res.data.priceTime = []);
        this.formInfo = res.data;
        if (this.isCreateNew) { // 再次发起（复制）回填新的创建人信息
          this.initData();
        }
        // 回填已选账号
        this.$refs['flyLinkedAccountRef'].setAccountData(this.formInfo.queryPriceAdvises || []);
      }).catch(err => {
        console.log(err);
      });
    },
    // 获取部门列表
    queryDeptTreeList() {
      getDepartmentAll().then(res => {
        this.deptTreeList = (res && res.data) || [];
      }).catch(e => {
        console.log(e);
      });
    },
    // 发起询价
    handleCreate() {
      this.$refs['formInfo'].validate(valid => {
        const selectedAccountArr = this.$refs['flyLinkedAccountRef'].selectedData;
        if (valid) {
          if (!selectedAccountArr.length) {
            this.$message.warning('请选择询价账号');
            return;
          }
          showModal('确定发起询价？').then(() => {
            this.submit(selectedAccountArr);
          }).catch(() => {
            return false;
          });
        } else {
          this.$message.warning('请检查信息是否完整');
        }
      });
    },
    // 保存草稿
    saveDraft() {
      showModal('是否保存草稿?', '', {
        iconClass: 'del-icon'
      }).then(() => {
        this.submit(this.$refs['flyLinkedAccountRef'].selectedData, true);
      }).catch(() => {
        return false;
      });
    },
    submit(data = [], isDraft = false) {
      const params = Object.assign({}, this.formInfo);
      params.queryPriceAdvises = [];
      data.forEach(el => {
        params.queryPriceAdvises.push({
          wxUserId: el.wxUserId,
          accountId: el.accountId,
          accountName: el.accountName
        });
      });
      if (isDraft) { params.isDraft = true; }
      if (params.priceTime && params.priceTime.length === 2) {
        params.priceStartTime = params.priceTime[0] / 1000;
        params.priceEndTime = params.priceTime[1] / 1000;
      }
      delete params.priceTime;
      if (this.id && !this.isCreateNew && !isDraft) {
        this.edit(params);
      } else {
        this.add(params, isDraft);
      }
    },
    add(params = {}, isDraft = false) {
      if (params.id && (!isDraft || this.isCreateNew)) {
        delete params.id;
      }
      if (params.sn && this.isCreateNew) {
        delete params.sn;
      }
      isDraft ? this.draftLoading = true : this.addLoading = true;
      queryPriceCreate(params).then(res => {
        if (res.code !== 200) {
          this.$message.error(res.message);
        }
        if (isDraft) {
          this.$router.push({
            name: 'flyPrice'
          });
        } else {
          this.$router.push({
            name: 'flyPriceDetail',
            query: {
              id: res.data
            }
          });
        }
        isDraft ? this.draftLoading = false : this.addLoading = false;
        this.handleAccountLoading();
      }).catch(err => {
        this.handleAccountLoading();
        isDraft ? this.draftLoading = false : this.addLoading = false;
        console.log(err);
      });
    },
    edit(params) {
      queryPriceCreate(params).then(res => {
        if (res.code !== 200) {
          this.$message.error(res.message);
        }
        this.$router.push({
          name: 'flyPriceDetail',
          query: {
            id: this.id
          }
        });
        this.handleAccountLoading();
      }).catch(err => {
        this.handleAccountLoading();
        console.log(err);
      });
    },
    handleAccountLoading() {
      this.$refs['flyLinkedAccountRef'].handleAccountLoading();
    },
    previewFields() {
      this.$refs.previewFields.openDialog();
    },
    toBack() {
      if (this.$route.meta.isDetail) {
        this.$router.push({
          name: 'flyPriceDetail',
          query: {
            id: this.id
          }
        });
        return;
      }
      this.$router.push({
        name: 'flyPrice'
      });
    }
  }
};
</script>
<style lang="scss" scoped>
.sign-detail-container{
		margin:	16px 16px 0;
		background: #fff;
		min-height: calc(100vh - 64px);
    padding-bottom: 56px;
		.sign-detail-content{
			padding: 16px 24px 0 0;
      &::v-deep {
        .el-form-item__label{
          color:#666666;
        }
      }
      .creator {
        ::v-deep .el-form-item__label{
            color:#999999;
          }
      }
		}
    .textarea-class {
      &::v-deep {
        .el-input__inner{
          width: 240px;
        }
        .el-textarea .el-textarea__inner{
          width: 240px;
          height: 88px;
        }
      }
    }
    .width240 {
      width: 240px;
      &::v-deep {
        .el-select {
          width: 240px;
        }
        .el-tag{
          color: #406EFF;
          background: #EFF3FB;
        }
        .el-input__inner {
          width: 240px;
        }
       .el-textarea__inner{
          height: 88px;
        }
      }
    }
    .empty-btn-style {
      border-color: #406EFF;
      background: #fff;
      color: #406EFF;
    }
	}
.mobile-create {
  border-radius: 6px;
  .sign-detail-content {
    padding-left: 12px !important;
    padding-right: 12px !important;
  }
  &::v-deep {
    .el-form-item__label {
      color: #999999 !important;
    }
  }
}
.flex-wrap {
  flex-wrap: wrap;
}
</style>
